package com.servlet;

import com.dao.UserDao;
import com.entity.User;
import com.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author admin
 */
@WebServlet({"/LoginServlet.filter","/LoginOut.filter"})
public class LoginServlet extends HttpServlet {
//    private  String encoding;

    private User user = new User();


    @Override
    public void init() throws ServletException {
        //初始化字符编码
//        encoding = this.getServletContext().getInitParameter("encoding");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding(encoding);//设置请求编码格式
        System.out.println("LoginServlet");
        String method = request.getParameter("method");
        if (method.equals("login")) {
            this.login(request,response);
        }else if (method.equals("loginOut")){
            this.loginOut(request,response);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }


    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        user.setU_name(userName);
        user.setU_pwd(userPwd);
        System.out.println(user);
        SqlSession session = MybatisUtil.getSession();
        UserDao userDao = session.getMapper(UserDao.class);
        System.out.println("userDao:"+userDao);
        User user1 = userDao.login(user);
        System.out.println(user1);
        //判断是否在数据库中查询到user
        if(user!=null){
            request.getSession().setAttribute("user",user1);
            request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request,response);
//            response.sendRedirect(request.getContextPath()+"/IndexInServlet.filter");
        }else{
            request.getRequestDispatcher("/error.jsp").forward(request,response);
        }
    }

    private void loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }
}
